package com.javabasic.algorithm.leetcode;

import javax.validation.TraversableResolver;
import java.util.ArrayList;
import java.util.List;

/**
 * @author mir.xiong
 * @version 1.0
 * @description
 * @see     [2415. 反转二叉树的奇数层 - 力扣（LeetCode）](https://leetcode.cn/problems/reverse-odd-levels-of-binary-tree/description/?envType=daily-question&envId=2023-12-15)
 * @since Created by work on 2023/12/16 01:47
 */
public class ReverseOddLevelsOfBinaryTree {

    public TreeNode reverseOddLevels(TreeNode root) {
        if (root == null) {
            return root;
        }

        int tag = 1;
        List<TreeNode> commonLevelNode = new ArrayList<>();
        List<TreeNode> tempCommonLevelNode;
        int commonLevelLen;
        int commonLevelLenOfHalf;
        commonLevelNode.add(root);
        while (!commonLevelNode.isEmpty()) {

            if (tag%2 == 0) {
                commonLevelLen = commonLevelNode.size();
                commonLevelLenOfHalf = commonLevelLen /2;
                for (int i = 0; i < commonLevelLenOfHalf; i++) {
                    swap(commonLevelNode.get(i), commonLevelNode.get(commonLevelLen-1-i));
                }

            }

            tempCommonLevelNode = new ArrayList<>();
            for (TreeNode treeNode : commonLevelNode) {
                if (treeNode.right != null) {
                    tempCommonLevelNode.add(treeNode.right);
                }
                if (treeNode.left != null) {
                    tempCommonLevelNode.add(treeNode.left);
                }
            }

            commonLevelNode = tempCommonLevelNode;
            tag ++;
        }

        return root;

    }

    private void swap(TreeNode treeNode1, TreeNode treeNode2) {
        int temp = treeNode1.val;
        treeNode1.val = treeNode2.val;
        treeNode2.val = temp;
    }

}

